package com.marvels.common.interceptor;

import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.utils.MarvelsUtils;
import com.marvels.common.utils.ThreadContextUtil;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 日志拦截器
 * 在独立线程请求中记录uuid，用来跟踪日志
 * @author wangliang
 *
 */

public class MarvelsLogInterceptor implements HandlerInterceptor {
	

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		ThreadContext.remove(MarvelsConstant.THREAD_UUID_KEY);
		ThreadContext.remove(MarvelsConstant.REQUEST_URL_KEY);
		ThreadContextUtil.removeAll();
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		//Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		String uuid = generateUUID();
		String requestUrl = arg0.getRequestURL().toString();
		ThreadContext.put(MarvelsConstant.THREAD_UUID_KEY, uuid);
		ThreadContext.put(MarvelsConstant.REQUEST_URL_KEY, requestUrl);
		String ip = MarvelsUtils.getIpAddr(arg0);
		ThreadContextUtil.set(MarvelsConstant.USER_IP, ip);
		ThreadContextUtil.set(MarvelsConstant.THREAD_UUID_KEY, uuid);
		ThreadContextUtil.set(MarvelsConstant.REQUEST_URL_KEY, requestUrl);
		return true;
	}
	
	private String generateUUID(){
		return String.valueOf(UUID.randomUUID());
	}
	
}
